package com.aurora.source.util.netutil;

import com.aurora.source.BuildConfig;
import com.aurora.source.source.SourceApplication;
import com.aurora.source.util.LogUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * OkHttp3 工具类
 * <p>
 * Created by Lance on 2018/7/6 11:36
 */
public class OkHttpUtil {

    private static OkHttpClient sOkHttpClient;

    //设置缓存目录
    private static final File sCacheDirectory = new File(SourceApplication.getInstance()
            .getCacheDir().getAbsolutePath(), "httpCache");

    private static Cache sCache = new Cache(sCacheDirectory, 10 * 1024 * 1024);

    public static OkHttpClient getOkHttpClient() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                LogUtils.i(message);
            }
        });
        if (sOkHttpClient == null) {
            if (BuildConfig.DEBUG) {
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            }
            sOkHttpClient = new OkHttpClient.Builder()
                    .cookieJar(CookieJar.NO_COOKIES)
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .addInterceptor(new ChenchenIntercepter())
                    .addInterceptor(logging)
                    //.cookieJar(new CookiesManager())
                    .cache(sCache)
                    .build();
        }
        return sOkHttpClient;
    }

    //自定义拦截器
    private static class ChenchenIntercepter implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request oldRequest = chain.request();
            HttpUrl.Builder builder = oldRequest.url()
                    .newBuilder()
                    .scheme(oldRequest.url().scheme())
                    .host(oldRequest.url().host());
//                    //公共参数
//                    .addQueryParameter("claentType", "ANDROID");

            Request newRequest = oldRequest.newBuilder()
                    .method(oldRequest.method(), oldRequest.body())
                    //.header("Content-Type", "application/json")
                    .url(builder.build())
                    .build();

            Response response = chain.proceed(newRequest);

            return response;
        }
    }

    //Cookie设置
    static HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    private static class CookiesManager implements CookieJar {

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            cookieStore.put(url.host(), cookies);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            List<Cookie> cookies = cookieStore.get(url.host());
            return cookies != null ? cookies : new ArrayList<Cookie>();
        }
    }

}
